function orthsdm(filename, newfilename)
% orthsdm  - orthogonalize SDM object in file
%
% FORMAT:       orthsdm(filename [, newfilename]);
%
% Input fields:
%
%       filename    SDM file
%       newfilename SaveAs filename (default: *_orth.sdm)
%
% No output fields

% Version:  v0.7a
% Build:    7082721
% Date:     Aug-27 2007, 9:39 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~ischar(filename) || ...
    isempty(filename)
    error( ...
        'BVQXtools:BadArgument', ...
        'Valid matrix of vectors without Inf/Nans are required.' ...
    );
end
filename = filename(:)';
if nargin < 2 || ...
   ~ischar(newfilename) || ...
    isempty(newfilename)
    [fp{1:3}] = fileparts(filename);
    if isempty(fp{1})
        fp{1} = '.';
    end
    newfilename = [fp{1} filesep fp{2} '_orth.sdm'];
end

% try loading SDM
sdm = [];
sdml = true;
try
    [sdm, sdml] = BVQXfile(filename);
    if ~isBVQXfile(sdm, 'sdm')
        error('NO_SDM');
    end
catch
    if isBVQXfile(sdm, true) && ...
        sdml
        sdm.ClearObject;
    end
    error( ...
        'BVQXtools:BadArgument', ...
        'No SDM file loadable.' ...
    );
end

% orthogonalize SDMMatrix
if sdm.FirstConfoundPredictor < 1 || ...
    sdm.FirstConfoundPredictor > size(sdm.SDMMatrix, 2)
    sdm.SDMMatrix = orthvecs(sdm.SDMMatrix);
else
    sdm.SDMMatrix(:, 1:sdm.FirstConfoundPredictor-1) = ...
        orthvecs(sdm.SDMMatrix(:, 1:sdm.FirstConfoundPredictor-1));
end

% SaveAs
sdm.SaveAs(newfilename);
if sdml
    sdm.ClearObject;
end
